package fr.zenexity.transportInParis;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;


public class BrowsingCanvas extends Canvas {

    public static final int BACKGROUND_COLOUR = 16711680;
    private int x = 0;
    private int paddingSize = 50;
    private int y = 0;
    private int maxDisplayWidth;
    private int maxDisplayHeight;
    private Image image;

    public BrowsingCanvas(Image image) {
        super();
        this.changeImage(image);
    }

    private void initBounds() {
        this.x = -this.image.getHeight() / 2 + this.getHeight();
        this.y = -this.image.getWidth() / 2 + this.getWidth();
        this.maxDisplayHeight = this.image.getHeight() - this.getHeight();
        this.maxDisplayWidth = this.image.getWidth() - this.getWidth();
    }
//	protected void paint(Graphics g) {
//		g.setColor(BACKGROUND_COLOUR);
//		this.paintImage(g);
//	}

    public void paint(Graphics g) {
        g.drawImage(image, x, y, Graphics.LEFT | Graphics.TOP);
    }

    public void changeImage(Image newImage) {
        this.image = newImage;
        this.initBounds();
        this.setFullScreenMode(true);
        this.repaint();
    }

    public void translateRight() {
        x -= paddingSize;
        x = Math.max(x, -this.maxDisplayWidth);
        this.repaint();
    }

    public void translateLeft() {
        x += paddingSize;
        x = Math.min(x, 0);
        this.repaint();
    }

    public void translateUp() {
        y += paddingSize;
        y = Math.min(y, 0);
        this.repaint();
    }

    public void translateDown() {
        y -= paddingSize;
        y = Math.max(y, -this.maxDisplayHeight);
        this.repaint();
    }

    private void moveCanvas(int keyCode) {
        if (keyCode == -6) {
            // LEFT BUTTON
            this.setFullScreenMode(false);
        }
        if (keyCode == -1) {
            // UP
            this.translateUp();
        }

        if (keyCode == -2) {
            // DOWN
            this.translateDown();
        }

        if (keyCode == -3) {
            // LEFT
            this.translateLeft();
        }
        if (keyCode == -4) {
            // RIGHT
            this.translateRight();
        }
    }

    protected void keyRepeated(int keyCode) {
        this.moveCanvas(keyCode);
    }
     protected void keyPressed(int keyCode) {
        this.moveCanvas(keyCode);
    }
}